package edu.chl.dat255.bluebanana.presentation.impl;

import edu.chl.dat255.bluebanana.R;
import edu.chl.dat255.bluebanana.data.impl.DbConst;
import edu.chl.dat255.bluebanana.utils.DatabaseUtil;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;

public class Preferences extends PreferenceActivity implements
		OnPreferenceChangeListener {
	private String ringtone;
	private String messageTone;
	private long profileId;
	private SharedPreferences sharedPrefs;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences);

		profileId = getIntent().getLongExtra("Profile", -1);

		ringtone = DatabaseUtil.getTextValue(profileId,
				DbConst.KEY_RINGTONE_PATH, this);

		messageTone = DatabaseUtil.getTextValue(profileId,
				DbConst.KEY_MESSAGETONE_PATH, this);
		
		if (ringtone.equals("null")) {
			ringtone = RingtoneManager.getActualDefaultRingtoneUri(
					Preferences.this, RingtoneManager.TYPE_RINGTONE).toString();
		}
		
		if (messageTone.equals("null")) {
			messageTone = RingtoneManager.getActualDefaultRingtoneUri(
					Preferences.this, RingtoneManager.TYPE_NOTIFICATION).toString();
		}

		RingtonePreference ringtonePref = (RingtonePreference) findPreference("ringtonePref");
		ringtonePref.setPersistent(true);
		RingtonePreference notificationPref = (RingtonePreference) findPreference("notificationPref");
		notificationPref.setPersistent(true);

		ringtonePref.setOnPreferenceChangeListener(this);
		notificationPref.setOnPreferenceChangeListener(this);

		sharedPrefs = PreferenceManager
				.getDefaultSharedPreferences(Preferences.this);

		sharedPrefs.edit().putString("ringtonePref", ringtone).commit();
		sharedPrefs.edit().putString("notificationPref", messageTone).commit();
	}

	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue) {
		RingtonePreference ringtonePref = (RingtonePreference) preference;
		if (ringtonePref.getTitle().equals("Ringtones")) {
			newValue = newValue.toString();
			DatabaseUtil.sendValueToDatabase(profileId,
					DbConst.KEY_RINGTONE_PATH, newValue, Preferences.this);
		} else if (ringtonePref.getTitle().equals("Notification tones")) {
			newValue = newValue.toString();
			DatabaseUtil.sendValueToDatabase(profileId,
					DbConst.KEY_MESSAGETONE_PATH, newValue, Preferences.this);
		}
		return true;
	}
}
